<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>

<body>
    <script type="text/javascript" src="./lib/jquery.js"></script>
    <script type="text/javascript">
        function handleParam(obj) {
            var params = obj;
            var pstr = "";
            for (var key in params) {
                var k = key;
                var v = params[key];
                pstr = k + "=" + v + "&";
            }
            if (pstr.length > 0 && pstr.lastIndexOf("&") === pstr.length - 1) {
                pstr = pstr.substr(0, pstr.length - 1);
            }
            return pstr;
        }

        function ajax(options) {
            var xhr = new XMLHttpRequest();
            var pstr = handleParam(options.data);
            //获取到的数据.data
            if (options.type == "get") {
                options.url += "?" + pstr;
            }
            xhr.open(options.type, options.url);
            if (options.type == "get") {
                xhr.send(null);
            } else if (options.type == "post") {
                xhr.setRequestHeader(
                    "content-type",
                    "application/x-www-form-urlencoded"
                );
                xhr.send(pstr);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        // 服务端返回的原始数据是字符串
                        var res = xhr.responseText;
                        var obj = JSON.parse(res);
                        // 回调函数
                        options.success(obj);
                    }
                };
            }
        }
        ajax({
            type: "get",
            data: {
                id: 1,
                bookname: "西游记",
            },
            url: "http://www.liulongbin.top:3006/api/getbooks",
            success: function(res) {
                console.log(res);
            },
        });
    </script>
</body>

</html>